
import { _decorator, Component, Node, Collider, ITriggerEvent, AudioSource } from 'cc';
import { Constant } from '../framework/Constant';
const { ccclass, property, menu } = _decorator;

/**
 * Predefined variables
 * Name = SelfPlane
 * DateTime = Wed Feb 09 2022 19:57:33 GMT+0800 (中国标准时间)
 * Author = ashscc
 * FileBasename = SelfPlane.ts
 * FileBasenameNoExtension = SelfPlane
 * URL = db://assets/script/SelfPlane.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/en/
 *
 */
 
@ccclass('SelfPlane')
@menu('plane/SelfPlane')
export class SelfPlane extends Component {

    @property(Node)
    public explode: Node = null
    @property(Node)
    public blood: Node = null
    @property(Node)
    public bloodRoot: Node = null
    public lifeValue = 5

    public isPlayerDie = false
    private _playerBlood = 0
    private _audioSource: AudioSource = null

    start(){
        this.init()
        this._audioSource = this.getComponent(AudioSource)
    }

    public init(){
        this._playerBlood = this.lifeValue
        this.isPlayerDie = false
        this.blood.setScale(1, 1, 1)
        this.explode.active = false
    }
    
    onEnable(){
        const collider = this.node.getComponent(Collider)
        collider.on('onTriggerEnter', this._onTriggerEnter, this)
    }

    onDisable(){
        const collider = this.node.getComponent(Collider)
        collider.off('onTriggerEnter', this._onTriggerEnter, this)
    }

    private _onTriggerEnter(event: ITriggerEvent) {
        const otherColliderGroup = event.otherCollider.getGroup()
        if (otherColliderGroup === Constant.CollisionType.ENEMY_BULLET || otherColliderGroup === Constant.CollisionType.ENEMY_PLAYER){
            if(this._playerBlood === this.lifeValue) {
                this.bloodRoot.active = true
            }
            if(this._playerBlood <= 0){
                this.explode.active = true
                this._audioSource.play()
                this.isPlayerDie = true
                this.bloodRoot.active = false
            }else{
                this._playerBlood --
                this.blood.setScale(this._playerBlood/this.lifeValue, 1, 1)
            }
        }
    }


    // update (deltaTime: number) {
    //     // [4]
    // }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/en/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/en/scripting/life-cycle-callbacks.html
 */
